package com.util.seo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

import com.redfin.sitemapgenerator.ChangeFreq;
import com.redfin.sitemapgenerator.SitemapIndexGenerator;
import com.redfin.sitemapgenerator.WebSitemapGenerator;
import com.redfin.sitemapgenerator.WebSitemapUrl;

/**
 * 
 * @author freedomlei
 */
public class ReadAndWriteFile {

	/**
	 * 只读出目录，不读取内容
	 */
	public static void ReadZIP() {
		try {
			ZipFile zipFile = new ZipFile("E:\\demo\\demo在在.zip", "gbk");
			for (Enumeration e = zipFile.getEntries(); e.hasMoreElements();) {
				ZipEntry extry = (ZipEntry) e.nextElement();
				System.out.println(extry.getName());
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 生成Zip文件
	 * 
	 * @param out
	 * @param f
	 * @param base
	 * @throws FileNotFoundException
	 * @throws IOException
	 */

	private static void zip(ZipOutputStream out, File f, String base) throws FileNotFoundException, IOException {
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			out.putNextEntry(new ZipEntry(f.getName()));
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + fl[i].getName());
			}
		} else {
			/* 错误的原因在这，如果有设置Entry，就看不到文件，如果不是目录，就得不到，现修改正确 */
			// out.putNextEntry(new ZipEntry(base));
			if (!f.isFile())
				return;
			out.putNextEntry(new ZipEntry(f.getName()));
			FileInputStream in = new FileInputStream(f);
			int b;
			// System.out.println(base);
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
		}

	}

	/**
	 * 用传入值
	 * 
	 * @param zipFileName
	 * @param path
	 * @throws Exception
	 */
	public static void writeZIP(String zipFileName, String path, String fileUrls) throws Exception {

		String upload = "";// CommonConfig.getInstance().getParamete("Upload");
		String fpath = "";
		StringTokenizer st = null;
		if (zipFileName == null || fileUrls == null)
			return;
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
		st = new StringTokenizer(fileUrls, ",");
		while (st.hasMoreTokens()) {
			fpath = st.nextToken();
			File f = new File(upload + fpath);
			zip(out, f, "");
		}
		System.out.println("zip done");
		out.close();
	}

	/**
	 * 创建文件路径
	 * 
	 * @return
	 * @throws DataAccessException
	 */
	public String filePath() throws Exception {
		String filepath = "";
		String year = "";
		String month = "";
		// String day = "";
		// year = String.valueOf(DateComFunc.getYear());
		// month = String.valueOf(DateComFunc.getMonth());
		// day = String.valueOf(DateComFunc.getDay());

		filepath = filepath + year + "\\" + month + "\\";
		return filepath;
	}

	public static void main(String[] args) {
		String webDir = "/web/www/cms/news/beijing";
		String saveSiteMapDir = "/web/www/cms/news/";
		List arrayList = ReadAndWriteFile.getListFiles(webDir, true);

		if (arrayList.isEmpty()) {
			System.out.println("没有符号要求的文件");
		} else {
			try {
				boolean file = new ReadAndWriteFile().getSite(arrayList, saveSiteMapDir, webDir);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// try {
		// // ReadZIP();
		// String filepath =
		// ",2008\\1\\9\\33\\66\\d869901\\869901.txt,2008\\1\\9\\新建 Text Document.txt";
		// writeZIP("E:\\demo\\aaa.zip", "", filepath);
		// } catch (Exception ex) {
		// ex.printStackTrace();
		// }
	}

	public static boolean createSiteMap(String webDir, String saveSiteMapDir) {
		boolean flag = false;
		List arrayList = ReadAndWriteFile.getListFiles(webDir, true);
		if (arrayList.isEmpty()) {
			System.out.println("没有符号要求的文件");
		} else {
			try {
				flag = getSite(arrayList, saveSiteMapDir, webDir);
			} catch (Exception e) {
				flag = false;
				e.printStackTrace();
			}
		}
		return flag;
	}

	// /**
	// * 取文件列表
	// * @param f
	// * @param suffix
	// * @param isdepth
	// * @return
	// */
	// public static List listFile(File f, boolean isdepth) {
	// // 是目录，同时需要遍历子目录
	// if (f.isDirectory() && isdepth == true) {
	// File[] t = f.listFiles();
	// for (int i = 0; i < t.length; i++) {
	// listFile(t[i], isdepth);
	// }
	// } else {
	// String filePath = f.getAbsolutePath();
	//
	// int begIndex = filePath.lastIndexOf(".");// 最后一个.(即后缀名前面的.)的索引
	// String tempsuffix = "";
	// if (begIndex != -1) {// 防止是文件但却没有后缀名结束的文件
	// tempsuffix = filePath.substring(begIndex + 1, filePath.length());
	// }
	// if (tempsuffix.equals("html") || tempsuffix.equals("shtml")) {
	// fileList.add(filePath);
	// }
	// }
	// return fileList;
	// }

	/**
	 * 方法追加文件：使用FileWriter
	 * 
	 * @param fileName
	 * @param content
	 */
	public static void appendMethod(String fileName, String content) {
		try {
			// 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
			FileWriter writer = new FileWriter(fileName, true);
			writer.write(content + "\r\n");
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 创建siteMap文件
	 * 
	 * @param list
	 * @param saveSiteMapDir
	 * @throws MalformedURLException
	 */
	public static boolean getSite(List list, String saveSiteMapDir, String surl) {
		boolean flag = false;
		try {
			File myDir = new File(saveSiteMapDir);
			WebSitemapGenerator wsg = new WebSitemapGenerator("http://beijing.fantong.com", myDir);

			if (list != null)
				for (Iterator<String> ite = list.iterator(); ite.hasNext();) {
					String str = ite.next();
					int index = surl.length();
					if (str.indexOf(surl) != -1)
						str = str.substring(index - 1, str.length());
					// if(str.startsWith("http://beijing.fantong.com"))
					wsg.addUrl("http://beijing.fantong.com" + str);
				}
			wsg.write();
			flag = true;
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 建立siteMap文件，并具有更新时间
	 * 
	 * @throws MalformedURLException
	 */
	public static void getSiteMap() throws MalformedURLException {
		File myDir = new File("c:/SiteMap/");
		WebSitemapGenerator wsg = new WebSitemapGenerator("http://www.fantong.com", myDir);
		WebSitemapUrl url = new WebSitemapUrl.Options("http://www.fantong.com/index.html").lastMod(new Date()).priority(1.0).changeFreq(ChangeFreq.HOURLY).build();
		wsg.addUrl(url); // repeat multiple times
		wsg.write();
	}

	// public static List<String> fileList = new ArrayList<String>();
	/**
	 * 多个siteMap建立索引文件
	 * 
	 * @throws MalformedURLException
	 */
	public static void getWebSiteMap() throws MalformedURLException {
		File myDir = new File("c:/SiteMap/");
		File myFile = new File("c:/SiteMap/aa.xml");
		String type[] = new String[] { "order", "food", "dazhe", "report", "vip", "view", "party", "coupon", "keyman", "hot", "fift" };
		WebSitemapGenerator wsg;
		// generate foo sitemap
		wsg = WebSitemapGenerator.builder("http://beijing.fantong.com", myDir).fileNamePrefix("cuxiao").build();
		for (int i = 1; i < 100; i++)
			wsg.addUrl("http://beijing.fantong.com/cuxiao/" + i);
		wsg.write();
		// generate bar sitemap
		wsg = WebSitemapGenerator.builder("http://beijing.fantong.com", myDir).fileNamePrefix("huodong").build();
		for (int i = 1; i < 100; i++)
			wsg.addUrl("http://beijing.fantong.com/huodong/" + i);
		wsg.write();
		// generate sitemap index for foo + bar
		SitemapIndexGenerator sig = new SitemapIndexGenerator("http://beijing.fantong.com", myFile);
		sig.addUrl("http://beijing.fantong.com/cuxiao/cuxiao.xml");
		sig.addUrl("http://beijing.fantong.com/huodong/huodong.xml");
		sig.write();
	}

	// public static List getListFiles(String path, boolean isdepth) {
	// File file = new File(path);
	// return ReadAndWriteFile.listFile(file,isdepth);
	// }
	public static List getListFiles(String path, boolean isdepth) {
		File file = new File(path);
		List<String> fileList = new ArrayList<String>();
		return ReadAndWriteFile.listFile(file, isdepth, fileList);
	}

	// private static List<String> fileList = new ArrayList<String>();
	/**
	 * 取文件列表
	 * 
	 * @param f
	 * @param suffix
	 * @param isdepth
	 * @return
	 */
	public static List listFile(File f, boolean isdepth, List fileList) {

		// 是目录，同时需要遍历子目录
		if (f.isDirectory() && isdepth == true) {
			File[] t = f.listFiles();
			for (int i = 0; i < t.length; i++) {
				listFile(t[i], isdepth, fileList);
			}
		} else {
			String filePath = f.getAbsolutePath();
			int begIndex = filePath.lastIndexOf(".");// 最后一个.(即后缀名前面的.)的索引
			String tempsuffix = "";
			if (begIndex != -1) {// 防止是文件但却没有后缀名结束的文件
				tempsuffix = filePath.substring(begIndex + 1, filePath.length());
			}
			if (tempsuffix.equals("html") || tempsuffix.equals("shtml")) {
				fileList.add(filePath);
			}
		}
		return fileList;
	}

}